package com.xuan.service.impl;

import com.xuan.entity.po.Roles;
import com.xuan.entity.po.UserRoles;
import com.xuan.entity.result.Result;
import com.xuan.enums.UserRoleEnum;
import com.xuan.mapper.RolesMapper;
import com.xuan.mapper.UserRolesMapper;
import com.xuan.service.IRolesService;
import com.xuan.service.IUserRolesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuan.utils.SnowflakeIdGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xuan
 * @since 2025-06-12
 */
@Service
public class UserRolesServiceImpl extends ServiceImpl<UserRolesMapper, UserRoles> implements IUserRolesService {
    @Autowired
    private IRolesService rolesService;
    @Autowired
    private SnowflakeIdGenerator snowflakeIdGenerator;
    @Autowired
    private UserRolesMapper userRolesMapper;
    /**
     * 根据用户id获取角色等级
     * @param userId
     * @return
     */
    @Override
    public Result<String> getUserRoleCode(Long userId) {
        System.err.println("getUserRoleCode" + " " + userId);
        // 1.在用户角色关联表中，根据用户id查询角色id
        UserRoles userRoles = this.query().eq("user_id", userId).one();
        if (ObjectUtils.isEmpty(userRoles)) {
            return Result.error("用户不存在");
        }
        // 2.根据角色id查询角色等级
        Roles roles = rolesService.getById(userRoles.getRoleId());

        return Result.success(roles.getRoleCode());
    }

    /**
     * 绑定默认角色（普通用户）
     * @param userId
     */
    @Override
    public void bindDefaultRole(Long userId) {
        // 1.生成标识id
        long id = snowflakeIdGenerator.generateId();
        // 2.插入用户角色关联表
        UserRoles userRoles = new UserRoles();
        userRoles.setId(id);
        userRoles.setUserId(userId);
        userRoles.setRoleId(UserRoleEnum.USER.getCode());
        this.save(userRoles);
    }

    /**
     * 超管调用：升级用户为管理员
     * @param userId
     */
    @Override
    public void upgradeToAdmin(Long userId) {
        this.update().eq("user_id", userId).set("role_id", UserRoleEnum.ADMIN.getCode());
    }

    /**
     * 超管调用：降级用户为普通角色
     * @param userId
     */
    @Override
    public void downgradeToUser(Long userId) {
        this.update().eq("user_id", userId).set("role_id", UserRoleEnum.USER.getCode());
    }

    /**
     * 管理员调用：查询所有普通用户
     * @return
     */
    @Override
    public Result<List<Long>> getAllCommonUser() {
        List<Long> list = userRolesMapper.selectByRoleId(UserRoleEnum.USER.getCode());
        return Result.success(list);
    }

    /**
     * 管理员调用：查询所有用户
     * @return
     */
    @Override
    public Result<List<UserRoles>> getAllUser() {
        List<UserRoles> list = userRolesMapper.selectAllUser();
        return Result.success(list);
    }
}
